﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;

namespace QiAdmin.Core
{
    public class ExceptionFilter : IAsyncExceptionFilter
    {
        Action<string, string, Exception>? _action;
        public ExceptionFilter(Action<string, string, Exception> action)
        {
            _action = action;
        }
        public ExceptionFilter()
        {
        }
        public Task OnExceptionAsync(ExceptionContext context)
        {
            // 如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false)
            {
                if (_action != null)
                {
                    _action(((ControllerActionDescriptor)context.ActionDescriptor).ControllerName, ((ControllerActionDescriptor)context.ActionDescriptor).ActionName, context.Exception);
                }
                if (context.Exception.HResult == 1)
                {
                    context.Result = new ApiJsonResult(ResultType.Error, context.Exception.Message);
                }
                else
                {
                    if (App.Environment.IsDevelopment())
                    {
                        context.Result = new ApiJsonResult(ResultType.Error, "系统异常:" + context.Exception.Message);
                    }
                    else
                    {
                        context.Result = new ApiJsonResult(ResultType.Error, "系统异常:请联系管理员或稍后再试");
                    }
                }
            }
            // 设置为true，表示异常已经被处理了
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
